package com.houweishi.module.salary.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.houweishi.common.annotation.Excel;
import com.houweishi.module.copy.domain.BizCopy;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.houweishi.common.annotation.Log;
import com.houweishi.common.core.controller.BaseController;
import com.houweishi.common.core.domain.AjaxResult;
import com.houweishi.common.enums.BusinessType;
import com.houweishi.module.salary.domain.BizSalary;
import com.houweishi.module.salary.service.IBizSalaryService;
import com.houweishi.common.utils.poi.ExcelUtil;
import com.houweishi.common.core.page.TableDataInfo;

/**
 * 薪资Controller
 * 
 * @author houweishi
 * @date 2023-03-04
 */
@RestController
@RequestMapping("/module/salary")
public class BizSalaryController extends BaseController
{
    @Autowired
    private IBizSalaryService bizSalaryService;

    /**
     * 查询薪资列表
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizSalary bizSalary)
    {
        startPage();
        List<BizSalary> list = bizSalaryService.selectBizSalaryList(bizSalary);
        return getDataTable(list);
    }

    /**
     * 导出薪资列表
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:export')")
    @Log(title = "薪资", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizSalary bizSalary)
    {
        List<BizSalary> list = bizSalaryService.selectBizSalaryList(bizSalary);
        ExcelUtil<BizSalary> util = new ExcelUtil<BizSalary>(BizSalary.class);
        util.exportExcel(response, list, "薪资数据");
    }



    /**
     * 获取薪资详细信息
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizSalaryService.selectBizSalaryById(id));
    }

    /**
     * 新增薪资
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:add')")
    @Log(title = "薪资", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizSalary bizSalary)
    {
        return toAjax(bizSalaryService.insertBizSalary(bizSalary));
    }

    /**
     * 修改薪资
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:edit')")
    @Log(title = "薪资", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizSalary bizSalary)
    {
        return toAjax(bizSalaryService.updateBizSalary(bizSalary));
    }

    /**
     * 删除薪资
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:remove')")
    @Log(title = "薪资", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizSalaryService.deleteBizSalaryByIds(ids));
    }

    /**
     * 生成上个月工资表基本信息
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:add2')")
    @Log(title = "薪资", businessType = BusinessType.INSERT)
    @PostMapping("/post/add2")
    public AjaxResult add2(BizSalary bizSalary)
    {
        return toAjax(bizSalaryService.insertAndCountBizSalary(bizSalary));
    }


    /**
     * 每个员工薪资计算（上个月）
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:edit2')")
    @Log(title = "薪资", businessType = BusinessType.UPDATE)
    @PutMapping("/put/edit2")
    public AjaxResult edit2(@RequestBody BizSalary bizSalary)
    {
        return toAjax(bizSalaryService.updateBizSalary2(bizSalary));
    }

    /**
     * 根据薪资计算截止日期导出薪资列表（薪资计算截止日期必传）
     */
//    @PreAuthorize("@ss.hasPermi('module:salary:export')")
    @Log(title = "员工薪资", businessType = BusinessType.EXPORT)
    @PostMapping("/post/export2")
    public void export2(HttpServletResponse response, BizSalary bizSalary)
    {
        List<BizSalary> list = bizSalaryService.selectBizSalaryListBySalaryTime(bizSalary);
        ExcelUtil<BizSalary> util = new ExcelUtil<BizSalary>(BizSalary.class);
        util.exportExcel(response, list, "薪资数据");
    }


    /**
     * 自定义字段导出薪资
     */
//    @PreAuthorize("@ss.hasPermi('module:copy:export2')")
    @Log(title = "自定义导出薪资")
    @GetMapping("/get/export2")
    public void export3(HttpServletResponse response, BizSalary bizSalary) throws IllegalAccessException, IOException, ParseException {

        List<BizSalary> list = bizSalaryService.selectBizSalaryList(bizSalary);

        //创建HSSFWorkbook（excel文档对象）
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet对象（excel表单）
        HSSFSheet sheet = wb.createSheet("薪资");

        //字符串分割，并把String[]转换为list
        //        String[] fieldsNames = bizCopy.getFieldsNames().split(",");
        //        List<String> requestFields = Arrays.stream(fieldsNames).collect(Collectors.toList()) ;
        List<String> requestFields = StrUtil.split(bizSalary.getFieldsNames(),",");

        int startRow = 0;
        //表头
        HSSFRow rowHeader = sheet.createRow(startRow);
        Field[] fields = list.get(0).getClass().getDeclaredFields();
        for (int k = 0;k<requestFields.size();k++){
            String str = requestFields.get(k);
            Field field = Arrays.stream(fields).filter(x-> StrUtil.equals(x.getName(),str,true)).findFirst().get();
            HSSFCell cell3 = rowHeader.createCell(k);
            if(field.getAnnotation(Excel.class) != null){
                cell3.setCellValue(field.getAnnotation(Excel.class).name());
            }
        }
        for(BizSalary bizSalary1:list){
            startRow = startRow +1;
            //表内容
            HSSFRow rowContent = sheet.createRow(startRow);
            for(int k = 0;k<requestFields.size();k++){
                String str = requestFields.get(k);
                Field field = Arrays.stream(fields).filter(x-> StrUtil.equals(x.getName(),str,true)).findFirst().get();
                HSSFCell cell3 = rowContent.createCell(k);
                field.setAccessible(true);
                if(field.get(bizSalary1)!=null){
                    if(field.getAnnotation(JsonFormat.class) != null){
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US).parse(field.get(bizSalary1).toString());
                        String formattedDate = formatter.format(date);
                        cell3.setCellValue(formattedDate);//时间格式转换
                    }
                    else{ cell3.setCellValue(field.get(bizSalary1).toString());
                    }
                }
            }
        }
        String fileName = "薪资";
        //输出excel文件
        OutputStream output = response.getOutputStream();
        //设置Header和contentType,避免报错
        response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        wb.write(output);
        output.close();
    }

}
